package com.carmanage.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

import com.carmanage.dao.IStationDao;
import com.carmanage.domain.Station;
import com.carmanage.domain.StationInfo;


@Component
public class StationDaoImpl implements IStationDao {
	
	private SessionFactory sessionFactory;
	
	@Resource
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	public void save(Station station){
		Session session = sessionFactory.openSession();
		session.save(station);
		session.close();
	}
	
	public List<Station> findStations(){
		Session session = sessionFactory.openSession();
		Query query = session.createQuery("from Station");
		List<Station> stationList = query.list();
		System.out.println("staionList.size >>> "+stationList.size());
		session.close();
		return stationList;
	}

	
	public StationInfo findStationByName(String name) {
		Session session = sessionFactory.openSession();
		Query query = session.createQuery("from Station s where s.station_name = ?");
		query.setString(0, name);
		Station station = (Station)query.uniqueResult();
		StationInfo stationInfo = new StationInfo();
		
		stationInfo.setReal_num(station.getReal_num());
		Query query1 = session.createQuery("Select e.name from Employees e where e.stationname = ?");
		query1.setString(0,name);
		List<String> employeeName = query1.list();
		stationInfo.setStation_num(employeeName.size());
		stationInfo.setEmployeeName(employeeName);
		session.close();
		return stationInfo;
	}

	
	public void delectByName(String name) {
		Session session = sessionFactory.openSession();
		Query query = session.createQuery("delete from Station s where s.station_name = ?");
		query.setString(0,name);
		query.executeUpdate();
		session.close();
	}

	
	public void updateStation(Station station) {
		Session session = sessionFactory.openSession();
		Query query = session.createQuery("update from Station s set s.station_name = ?, s.station_location=?,s.station_num=?,s.real_num=? where s.station_id = ?");
		query.setString(0,station.getStation_name());
		query.setString(1,station.getStation_location());
		query.setInteger(2, station.getStation_num());
		query.setInteger(3, station.getReal_num());
		query.setInteger(4, station.getStation_id());
		query.executeUpdate();
		session.close();
		
	}

	public Station getStation(String name) {
		Session session = sessionFactory.openSession();
		Query query = session.createQuery("from Station s where s.station_name = ?");
		query.setString(0, name);
		Station station = (Station)query.uniqueResult();
		session.close();
		return station;
	}

}
